<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>表达式验证</title>
		<style type="text/css">
			* {
				margin: 0;
				padding: 0;
				box-sizing: border-box;
			}
			.w {
				width: 1200px;
				margin: 0 auto;
			}
			.box {
				width: 600px;
				height: 40px;
				margin: 30px auto;
				background-color: #ccc;
			}
			.box .item {
				padding: 2px 0;
				width: 100%;
				height: 40px;
			}
			.box .item label {
				display: inline-block;
				width: 60px;
				height: 35px;
				line-height: 35px;
				text-align: left;
			}
			.box .item input {
				width: 200px;
				height: 35px;
				padding-left: 5px;
				outline: none;
				border: 0;
				vertical-align: top;
			}
			.box .item .info {
				display: inline-block;
				width: 250px;
				height: 35px;
				line-height: 35px;
				vertical-align: middle;
			}
			.box .item .info .logo {
				display: inline-block;
				width: 15px;
				height: 15px;
				vertical-align: middle;
				margin-top: -5px;
			}
			.box .item .info .logo img {
				width: 100%;
				height: 100%;
				vertical-align: top;
				
			}
		</style>
	</head>
	<body>
		<div class="box">
			<div class="item">
				<label for="username">姓名：</label>
				<input type="text" name="" id="username" class="username" value="" />
				<span class="info">
					<i class="logo"><img src="img/mess.png"/></i>
					<span>请输入用户名</span>
				</span>
			</div>
		</div>
		<script type="text/javascript">
			var ipt  = document.querySelector('input');
			var logo = document.querySelector('img');
			var info = document.querySelector('.info span');
			var reg = /^[a-zA-Z0-9_-]{6,16}$/;		//姓名只能是英文字母、数字、_、-
			//当鼠标聚焦在输入框里面
			ipt.addEventListener('focus',function() {
				info.innerHTML = '姓名只能包含英文、数字 、-、_';
				logo.src = 'img/mess.png';
				this.style.border = '1px solid #1E90FF';
				this.style.boxShadow = '0 0 10px 2px rgba(0,0,0,0.1)'
			})
			//单鼠标离开输入框的时候,进行校验
			ipt.addEventListener('blur',function() {
				this.style.border = '0';
				this.style.boxShadow = '';
				if(reg.test(ipt.value)) {
					//输入正确
					info.innerHTML = '输入正确';
					logo.src = 'img/right.png';
				} else {
					logo.src = 'img/wrong.png';
					info.innerHTML  = '输入错误';
				}
			})
			
			
		</script>
	</body>
</html>
